package top.kaoshanji.p1ch04a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * 代码清单-p1ch04a-107页a：查找参数
 * URL访问地址：/parameterSnoop?action=lookup&word=obfuscate&word=onomatopoeia
 * @author kaoshanji
 * ^_^
 * create time 2025/4/3 18:57
 */
public class ParameterSnoop extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = resp.getWriter();

        out.println("Query String:");
        out.println(req.getQueryString());
        out.println();

        out.println("Request Parameters:");
        Enumeration<String> enumeration = req.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String [] values = req.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    out.println(name + " (" + i + "): " + values[i]);
                }
            }
        }
    }
}
